package com.xuetang.controller;

import com.xuetang.common.R;
import com.xuetang.entity.SysUser;
import com.xuetang.security.JwtTokenUtil;
import com.xuetang.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SysUserService userService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    /**
     * 微信小程序登录
     */
    @PostMapping("/login")
    public R<Map<String, Object>> login(@RequestBody Map<String, Object> loginData) {
        // 获取微信登录code
        String code = (String) loginData.get("code");
        // 获取用户信息
        Map<String, Object> userInfo = (Map<String, Object>) loginData.get("userInfo");

        System.out.println("收到登录请求 - code: " + code);
        System.out.println("用户信息: " + userInfo);

        // 打印用户信息详情
        if (userInfo != null) {
            System.out.println("nickName: " + userInfo.get("nickName"));
            System.out.println("avatarUrl: " + userInfo.get("avatarUrl"));
            System.out.println("gender: " + userInfo.get("gender"));
            System.out.println("country: " + userInfo.get("country"));
            System.out.println("province: " + userInfo.get("province"));
            System.out.println("city: " + userInfo.get("city"));
        }

        // 调用微信登录服务
        Map<String, Object> result = userService.wxLogin(code, userInfo);

        System.out.println("登录结果: " + result);

        if ((Boolean) result.getOrDefault("success", false)) {
            return R.success(result);
        } else {
            return R.error((String) result.getOrDefault("message", "登录失败"));
        }
    }

    /**
     * 后台管理系统登录
     */
    @PostMapping("/admin/login")
    public R<String> adminLogin(
            @RequestParam String username,
            @RequestParam String password) {
        // 模拟登录逻辑
        if ("admin".equals(username) && "123456".equals(password)) {
            return R.success("mock_admin_token");
        } else {
            return R.error("用户名或密码错误");
        }
    }

    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/profile")
    public R<Map<String, Object>> getUserInfo(@RequestHeader(value = "Authorization", required = false) String token) {
        // 从token中获取用户信息
        System.out.println("获取用户信息请求，token: " + token);

        try {
            // 从token中解析用户名
            if (token != null && token.startsWith("Bearer ")) {
                String actualToken = token.substring(7);
                String username = jwtTokenUtil.getUsernameFromToken(actualToken);

                if (username != null) {
                    // 根据用户名获取用户信息
                    SysUser user = userService.getUserByUsername(username);

                    if (user != null) {
                        Map<String, Object> userInfo = new HashMap<>();
                        userInfo.put("id", user.getId());
                        userInfo.put("username", user.getUsername());
                        userInfo.put("nickname", user.getNickname());
                        userInfo.put("avatar", user.getAvatar());
                        userInfo.put("gender", user.getGender());
                        userInfo.put("age", user.getAge());
                        userInfo.put("diabetesType", user.getDiabetesType());
                        userInfo.put("status", user.getStatus());

                        System.out.println("返回用户信息: " + userInfo);
                        return R.success(userInfo);
                    }
                }
            }

            // 如果无法从token获取用户信息，返回错误
            return R.error("获取用户信息失败");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取用户信息异常: " + e.getMessage());
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public R<Boolean> updateUserInfo(@RequestBody Map<String, Object> userInfo,
            @RequestHeader(value = "Authorization", required = false) String token) {
        System.out.println("更新用户信息请求：" + userInfo);
        System.out.println("token: " + token);

        // 打印接收到的用户信息
        if (userInfo != null) {
            System.out.println("nickname: " + userInfo.get("nickname"));
            System.out.println("avatar: " + userInfo.get("avatar"));
        }

        try {
            // 从token中解析用户名
            if (token != null && token.startsWith("Bearer ")) {
                String actualToken = token.substring(7);
                String username = jwtTokenUtil.getUsernameFromToken(actualToken);

                if (username != null) {
                    // 根据用户名获取用户信息
                    SysUser user = userService.getUserByUsername(username);

                    if (user != null) {
                        // 更新用户信息
                        if (userInfo.get("nickname") != null) {
                            user.setNickname((String) userInfo.get("nickname"));
                        }
                        if (userInfo.get("avatar") != null) {
                            user.setAvatar((String) userInfo.get("avatar"));
                        }

                        // 更新其他字段
                        if (userInfo.get("gender") != null) {
                            user.setGender(Integer.parseInt(userInfo.get("gender").toString()));
                        }
                        if (userInfo.get("age") != null) {
                            user.setAge(Integer.parseInt(userInfo.get("age").toString()));
                        }

                        // 保存更新
                        boolean result = userService.updateUserInfo(user);
                        return R.success(result);
                    }
                }
            }

            // 如果无法从token获取用户信息，返回错误
            return R.error("更新用户信息失败");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("更新用户信息异常: " + e.getMessage());
        }
    }
}